package com.xq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xq.entity.UmsUsers;
import com.xq.entity.User;
import com.xq.mapper.UmsUsersMapper;
import com.xq.mapper.UserMapper;
import com.xq.service.IUmsUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuven
 * @since 2025-05-21
 */
@Service
public class UmsUsersServiceImpl extends ServiceImpl<UmsUsersMapper, UmsUsers> implements IUmsUsersService {

    @Autowired
    private UmsUsersMapper umsUsersMapper;

    public UmsUsers getUserByUsername(String username) {
        QueryWrapper<UmsUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UmsUsers user = umsUsersMapper.selectOne(queryWrapper);
        return user;
    }

    /**
     * 根据手机号查找用户
     * @param phone
     * @return
     */
    public UmsUsers getUserByPhone(String phone) {
        QueryWrapper<UmsUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        UmsUsers user = umsUsersMapper.selectOne(queryWrapper);
        return user;
    }

    @Override
    public void setPhone(String phone) {
        //将手机号插入
        UmsUsers user = new UmsUsers();
        user.setMobile(phone);
        umsUsersMapper.insert(user);
    }

    @Override
    public int setUserAndPassword(UmsUsers user) {
        UpdateWrapper<UmsUsers> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("mobile",user.getMobile());//设置更新条件，手机号等于指定值的话则更新
        int update = umsUsersMapper.update(user, updateWrapper);
        return update;
    }

    @Override
    public UmsUsers findUserUnknown(String usernameOrPhone) {

        QueryWrapper<UmsUsers> queryWrapper = new QueryWrapper<>();
        //如果长度大于10就是手机号
        if (usernameOrPhone.length()>10){
            queryWrapper.eq("mobile",usernameOrPhone);
            UmsUsers user = umsUsersMapper.selectOne(queryWrapper);
            if (user==null){
                return null;
            }
            return user;
        }
        //如果小于等于10的话就是用户名
        queryWrapper.eq("username", usernameOrPhone);
        UmsUsers user = umsUsersMapper.selectOne(queryWrapper);
        if (user==null){
            return null;
        }
        return user;
    }
}
